import { getToken, removeToken, setToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { getImageUrl } from '@/utils/imageHandle'

// import defaultHead from '@/assets/morentou.jpg'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  type: '',
  userInfo: {},
  permissions: [],
  dics: {},
  goodsnum: 0
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_TYPE: (state, type) => {
    state.type = type
  },
  SET_USER: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  SET_DICS: (state, dics) => {
    state.dics = dics
  },
  SET_GOODSNUM: (state, goodsnum) => {
    state.goodsnum = goodsnum
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { token, callback, type } = userInfo
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      removeToken()
      resetRouter()
      commit('SET_TOKEN', token)
      setToken(token)
      resolve()
    })
  },

  // get user info
  getInfo({ commit, state }) {
    const user = getInfo()
    const dics = getDics()
    return Promise.all([user, dics]).then(result => {
      const { userName, profilePicture, userType, permissions } = result[0].data
      let avatar = {}
      if (profilePicture) {
        avatar = getImageUrl(profilePicture)
      }
      commit('SET_TYPE', userType)
      commit('SET_NAME', userName)
      commit('SET_USER', result[0].data)
      commit('SET_PERMISSIONS', permissions)
      commit('SET_AVATAR', avatar)
      commit('SET_DICS', result[1].data)
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_NAME', '')
        removeToken()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  getGoodsnum({ commit, state }) {
    getGoodsNum().then(data => {
      commit('SET_GOODSNUM', data.data)
    })
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
